package com.lc.activiti.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lc.activiti.config.Result;
import com.lc.activiti.config.WebSocketEncoder;
import com.lc.activiti.utils.redis.RedisUtil;
import lombok.Data;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Title: WebSocketServer
 * @Description:
 * @author: 骆超
 * @date: 2021/7/6 9:42
 */
@ServerEndpoint(value ="/webSocket/{userId}",encoders = { WebSocketEncoder.class })
@Component
@Data
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public static void sendMessage(String msgType,Session session, Object message) throws IOException, EncodeException {
        if (session != null) {
            synchronized (session) {
                if (message instanceof String){
                    session.getBasicRemote().sendObject(Result.success(message).setType("str"));
                }else{
                    session.getBasicRemote().sendObject(Result.success(message).setType(msgType));
                }
            }
        }
    }

    //给指定用户发送信息
    public static void sendInfo(String userName, String message) {
        Session session = sessionPools.get(userName);
        try {
            sendMessage(null,session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public static void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            if (ObjectUtil.isNull(userId)){
                sendMessage(null,session, null);
            }else{
                sessionPools.put(userId, session);
                addOnlineCount();
                System.out.println(RedisUtil.getUserName(userId) + "加入webSocket！当前人数为" + onlineNum);
                sendMessage(null,session, "欢迎" + RedisUtil.getUserName(userId) + "加入连接！");
            }
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    //关闭连接时调用
    @OnClose
    public static void onClose(@PathParam(value = "userId") String userId) {
        sessionPools.remove(userId);
        subOnlineCount();
        System.out.println(RedisUtil.getUserName(userId) + "断开webSocket连接！当前人数为" + onlineNum);
    }

    //在线消息
    @OnMessage
    public static void onMessage(String message) throws IOException {
        System.out.println(message);
        sessionPools.values().forEach(v->{
            try {
                sendMessage(null,v, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    public static void sendByUserIds(String message, List<String> userIds) {
        userIds.forEach(userId->{
            try {
                sendMessage(null, sessionPools.get(userId), message);
            } catch (IOException | EncodeException e) {
                e.printStackTrace();
            }
        });
    }

    public static void sendByUserId(String msgType,Object obj, Long userId){
        try {
            sendMessage(msgType, sessionPools.get(String.valueOf(userId)), obj);
        } catch (IOException | EncodeException e) {
            e.printStackTrace();
        }
    }

    //错误时调用
    @OnError
    public static void onError(Session session, Throwable throwable) {
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount() {
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }

}

